import { ref, computed, onMounted, markRaw } from 'vue';
import BpmnModeler from 'bpmn-js/lib/Modeler';
import type ElementRegistry from 'diagram-js/lib/core/ElementRegistry'
import type EventBus from 'diagram-js/lib/core/EventBus'
import { PropertiesUtil } from '../utils/PropertiesUtil';

// 定义属性面板组件
export function usePropertyPanel(props: { modeler: BpmnModeler }) {
  // 基础状态
  const selectedElement = ref<any>(null);
  const elementId = ref('');
  const elementName = ref('');
  const activeTab = ref('基础信息');

  // 流程基本属性
  const processId = ref('');
  const processName = ref('');
  const processDescription = ref('');

  // 用户任务属性
  const assignee = ref('');
  const candidateUsers = ref<string[]>([]);
  const candidateGroups = ref<string[]>([]);
  const dueDate = ref('');
  const formKey = ref('');

  // 审批模式
  const approvalMode = ref<'assignee' | 'candidate' | 'external'>('assignee');

  // 审批人为空时处理策略
  const emptyAssigneeStrategy = ref('');

  // 自动同意设置
  const autoApproveSettings = ref<string[]>([]);

  // 会签设置
  const isMultiInstance = ref(false);
  const multiInstanceType = ref<'sequential' | 'parallel'>('parallel');
  const completionCondition = ref('');

  // 条件表达式
  const conditionExpression = ref('');
  const conditionType = ref('normal'); // normal, default, conditional, builtinButton

  // 服务任务属性
  const serviceType = ref('class');
  const serviceValue = ref('');

  // 表单字段权限控制
  const formFieldPermissions = ref<Array<{
    fieldName: string;
    fieldLabel: string;
    permission: 'readonly' | 'editable' | 'hidden';
  }>>([]);

  // 操作权限控制（表格形式）
  const operationPermissions = ref([
    { name: '同意', alias: '同意', enabled: true, status: '审批通过' },
    { name: '拒绝', alias: '拒绝', enabled: true, status: '审批拒绝' },
    { name: '转交', alias: '转交', enabled: true, status: '审批中' },
    { name: '回退', alias: '回退', enabled: true, status: '已回退' },
    { name: '前加签', alias: '前加签', enabled: true, status: '审批中' },
    { name: '后加签', alias: '后加签', enabled: true, status: '审批中' }
  ]);

  // 计算属性
  const elementType = computed(() => selectedElement.value?.type || '');

  // 元素类型判断
  const isProcess = computed(() => elementType.value === 'bpmn:Process');
  const isTask = computed(() => /^bpmn:(?:User|Service|Script|Business|Manual|Receive)Task$/.test(elementType.value));
  const isUserTask = computed(() => elementType.value === 'bpmn:UserTask');
  const isServiceTask = computed(() => elementType.value === 'bpmn:ServiceTask');
  const isSequenceFlow = computed(() => elementType.value === 'bpmn:SequenceFlow');

  // 服务类型标签
  const serviceTypeLabel = computed(() => {
    switch (serviceType.value) {
      case 'class': return 'Java类名';
      case 'expression': return '表达式';
      case 'delegateExpression': return '代理表达式';
      default: return '实现类';
    }
  });

  // 内置按钮选项（基于操作权限）
  const builtinButtonOptions = computed(() => {
    return operationPermissions.value
      .filter(op => op.enabled)
      .map(op => ({
        label: op.alias || op.name,
        value: op.name,
        expression: `\${action == '${op.name}'}` // 默认的条件表达式格式
      }));
  });

  // 事件处理方法
  const updateProperty = (property: string, value: string) => {
    if (!selectedElement.value || !props.modeler) return;
    const modeling = props.modeler.get('modeling');
    // 克隆值以避免代理对象问题
    const newValue = Array.isArray(value) ? [...value] : value;
    PropertiesUtil.updateProperties(modeling, selectedElement.value, { [property]: newValue });
  };

  const updateFlowableProperty = (propertyName: string, value: any) => {
    if (!selectedElement.value || !props.modeler) return;
    const modeling = props.modeler.get('modeling');
    // 克隆值以避免代理对象问题
    const newValue = Array.isArray(value) ? [...value] : value;
    PropertiesUtil.updateFlowableProperty(modeling, selectedElement.value, propertyName, newValue);
  };

  // 手动事件处理
  const handleAssigneeChange = (value: string | string[]) => {
    assignee.value = Array.isArray(value) ? value[0] || '' : value;
    updateFlowableProperty('assignee', assignee.value);
  };

  const handleCandidateUsersChange = (value: string[]) => {
    candidateUsers.value = [...value];
    updateFlowableProperty('candidateUsers', candidateUsers.value.join(','));
  };

  const handleCandidateGroupsChange = (value: string[]) => {
    candidateGroups.value = [...value];
    updateFlowableProperty('candidateGroups', candidateGroups.value.join(','));
  };

  // 审批模式处理方法
  const updateApprovalMode = (mode: 'assignee' | 'candidate' | 'external') => {
    approvalMode.value = mode;
    updateFlowableProperty('approvalMode', mode);

    if (mode === 'assignee') {
      // 清空候选人员和外部接口相关设置
      candidateUsers.value = [];
      candidateGroups.value = [];
      updateFlowableProperty('candidateUsers', undefined);
      updateFlowableProperty('candidateGroups', undefined);
    } else if (mode === 'candidate') {
      // 清空指定人员和外部接口相关设置
      assignee.value = '';
      updateFlowableProperty('assignee', undefined);
    } else if (mode === 'external') {
      // 清空指定人员和候选人员设置
      assignee.value = '';
      candidateUsers.value = [];
      candidateGroups.value = [];
      updateFlowableProperty('assignee', undefined);
      updateFlowableProperty('candidateUsers', undefined);
      updateFlowableProperty('candidateGroups', undefined);
    }
  };

  // 审批人为空时处理策略方法
  const updateEmptyAssigneeStrategy = (value: string) => {
    emptyAssigneeStrategy.value = value;
    updateFlowableProperty('emptyAssigneeStrategy', value);
  };

  // 自动同意设置方法
  const updateAutoApproveSettings = (value: string[]) => {
    autoApproveSettings.value = [...value];
    updateFlowableProperty('autoApproveSettings', JSON.stringify(value));
  };

  const handleServiceTypeChange = (type: string) => {
    serviceType.value = type;
    updateServiceImplementation();
  };

  const updateServiceImplementation = () => {
    if (!selectedElement.value || !props.modeler) return;
    const modeling = props.modeler.get('modeling');
    PropertiesUtil.updateServiceImplementation(
      modeling,
      selectedElement.value,
      serviceType.value,
      serviceValue.value
    );
  };

  const updateConditionExpression = (value: string) => {
    if (!selectedElement.value || !props.modeler) return;

    try {
      const modeling = props.modeler.get('modeling') as any;
      const moddle = props.modeler.get('moddle') as any;

      if (!modeling || !moddle) {
        console.error('modeling or moddle is not available');
        return;
      }

      if (!value || value.trim() === '') {
        // 清空条件表达式
        modeling.updateProperties(selectedElement.value, {
          conditionExpression: null
        });
        return;
      }

      // 使用 moddle 创建条件表达式
      const expression = moddle.create('bpmn:FormalExpression', {
        body: value
      });

      modeling.updateProperties(selectedElement.value, {
        conditionExpression: expression
      });
    } catch (error) {
      console.error('updateConditionExpression error:', error);
    }
  };

  const updateConditionType = (type: string) => {
    conditionType.value = type;
    if (!selectedElement.value || !props.modeler) return;

    try {
      const modeling = props.modeler.get('modeling') as any;
      if (!modeling) {
        console.error('modeling is not available');
        return;
      }

      // 根据条件类型设置相应的属性
      switch (type) {
        case 'default':
          // 设置为默认流转路径 - 使用标准BPMN属性
          PropertiesUtil.setDefaultCondition(modeling, selectedElement.value, true);
          // 清除条件表达式
          conditionExpression.value = '';
          updateConditionExpression('');
          break;
        case 'conditional':
          // 清除默认标记
          PropertiesUtil.setDefaultCondition(modeling, selectedElement.value, false);
          break;
        case 'builtinButton':
          // 内置按钮本质上是条件流转路径，预设条件表达式
          PropertiesUtil.setDefaultCondition(modeling, selectedElement.value, false);
          // 可以根据操作权限设置预设的条件表达式
          break;
        case 'normal':
        default:
          // 普通流转路径，清除所有条件
          PropertiesUtil.setDefaultCondition(modeling, selectedElement.value, false);
          conditionExpression.value = '';
          updateConditionExpression('');
          break;
      }

      // 保存条件类型到扩展属性
      updateFlowableProperty('conditionType', type);
    } catch (error) {
      console.error('updateConditionType error:', error);
    }
  };

  // 表单字段权限控制方法
  const updateFormFieldPermissions = () => {
    if (!selectedElement.value || !props.modeler) return;
    const modeling = props.modeler.get('modeling');
    const permissionsData = {
      fields: formFieldPermissions.value
    };
    PropertiesUtil.updateFlowableProperty(modeling, selectedElement.value, 'formFieldPermissions', JSON.stringify(permissionsData));
  };

  // 添加表单字段
  const addFormField = () => {
    const newField = {
      fieldName: `field_${formFieldPermissions.value.length + 1}`,
      fieldLabel: `字段${formFieldPermissions.value.length + 1}`,
      permission: 'editable' as const
    };
    formFieldPermissions.value.push(newField);
    updateFormFieldPermissions();
  };

  // 删除表单字段
  const removeFormField = (index: number) => {
    formFieldPermissions.value.splice(index, 1);
    updateFormFieldPermissions();
  };

  // 更新字段权限
  const updateFieldPermission = (index: number, field: string, value: any) => {
    if (formFieldPermissions.value[index]) {
      (formFieldPermissions.value[index] as any)[field] = value;
      updateFormFieldPermissions();
    }
  };

  // 批量导入表单字段
  const importFormFields = (fields: Array<{fieldName: string; fieldLabel: string}>) => {
    const newFields = fields.map(field => ({
      fieldName: field.fieldName,
      fieldLabel: field.fieldLabel,
      permission: 'editable' as const
    }));
    formFieldPermissions.value.push(...newFields);
    updateFormFieldPermissions();
  };

  // 操作权限控制方法
  const updateOperationPermissions = () => {
    if (!selectedElement.value || !props.modeler) return;
    const modeling = props.modeler.get('modeling');
    const permissionsData = {
      operations: operationPermissions.value
    };
    PropertiesUtil.updateFlowableProperty(modeling, selectedElement.value, 'operationPermissions', JSON.stringify(permissionsData));
  };

  const updateOperationPermission = (index: number, field: string, value: any) => {
    if (operationPermissions.value[index]) {
      (operationPermissions.value[index] as any)[field] = value;
      updateOperationPermissions();
    }
  };

  // 会签设置方法（简化版本）
  const toggleMultiInstance = (enabled: boolean) => {
    isMultiInstance.value = enabled;
    updateMultiInstanceSettings();
  };

  const updateMultiInstanceType = (type: 'sequential' | 'parallel') => {
    multiInstanceType.value = type;
    updateMultiInstanceSettings();
  };

  const updateCompletionCondition = (value: string) => {
    completionCondition.value = value;
    updateMultiInstanceSettings();
  };

  const updateMultiInstanceSettings = () => {
    if (!selectedElement.value || !props.modeler) return;

    try {
      const modeling = props.modeler.get('modeling') as any;
      const bpmnFactory = props.modeler.get('bpmnFactory') as any;

      if (!bpmnFactory) {
        console.error('bpmnFactory is not available');
        return;
      }

      if (isMultiInstance.value) {
        // 使用bpmnFactory正确创建多实例循环特性
        const loopCharacteristics = bpmnFactory.create('bpmn:MultiInstanceLoopCharacteristics', {
          isSequential: multiInstanceType.value === 'sequential',
          // 设置默认集合变量和元素变量
          collection: '${assigneeList}',
          elementVariable: 'assignee'
        });


        // 设置完成条件
        if (completionCondition.value) {
          loopCharacteristics.completionCondition = bpmnFactory.create('bpmn:FormalExpression', {
            body: completionCondition.value
          });
        }
        // 应用多实例特性
        (modeling as any).updateProperties(selectedElement.value, {
          loopCharacteristics: loopCharacteristics
        });
      } else {
        // 移除多实例特性
        (modeling as any).updateProperties(selectedElement.value, {
          loopCharacteristics: undefined
        });
      }
    } catch (error) {
      console.error('更新会签设置失败:', error);
    }
  };

  // 加载元素属性
  const loadElementProperties = (element: any) => {
    if (!element) return;

    const businessObject = element.businessObject;
    if (!businessObject) return;

    // 加载基础属性
    elementId.value = element.id || '';
    elementName.value = businessObject.name || '';

    // 流程属性
    if (isProcess.value) {
      processId.value = businessObject.id || '';
      processName.value = businessObject.name || '';
    }

    // 用户任务属性
    if (isUserTask.value) {
      // 安全获取审批人相关属性
      const assigneeValue = getFlowableProperty(businessObject, 'assignee');
      const candidateUsersValue = getFlowableProperty(businessObject, 'candidateUsers');
      const candidateGroupsValue = getFlowableProperty(businessObject, 'candidateGroups');

      if (assigneeValue) {
        assignee.value = String(assigneeValue);
        candidateUsers.value = [];
        candidateGroups.value = [];
      } else {
        assignee.value = '';
        // 安全处理候选用户和候选组
        candidateUsers.value = candidateUsersValue ?
          String(candidateUsersValue).split(',').filter(user => user.trim()) : [];
        candidateGroups.value = candidateGroupsValue ?
          String(candidateGroupsValue).split(',').filter(group => group.trim()) : [];
      }

      dueDate.value = getFlowableProperty(businessObject, 'dueDate') || '';
      formKey.value = getFlowableProperty(businessObject, 'formKey') || '';

      // 加载审批模式
      const approvalModeValue = getFlowableProperty(businessObject, 'approvalMode');
      if (approvalModeValue && ['assignee', 'candidate', 'external'].includes(approvalModeValue)) {
        approvalMode.value = approvalModeValue as 'assignee' | 'candidate' | 'external';
      } else {
        // 根据已设置的属性推断审批模式
        if (assignee.value) {
          approvalMode.value = 'assignee';
        } else if (candidateUsers.value.length > 0 || candidateGroups.value.length > 0) {
          approvalMode.value = 'candidate';
        } else {
          approvalMode.value = 'assignee'; // 默认模式
        }
      }

      // 加载审批人为空时处理策略
      emptyAssigneeStrategy.value = getFlowableProperty(businessObject, 'emptyAssigneeStrategy') || '';

      // 加载自动同意设置
      const autoApproveSettingsStr = getFlowableProperty(businessObject, 'autoApproveSettings');
      if (autoApproveSettingsStr) {
        try {
          const settings = JSON.parse(String(autoApproveSettingsStr));
          autoApproveSettings.value = Array.isArray(settings) ? settings : [];
        } catch {
          autoApproveSettings.value = [];
        }
      } else {
        autoApproveSettings.value = [];
      }

      // 加载会签设置 - 只加载基础设置
      const loopCharacteristics = businessObject.loopCharacteristics;
      if (loopCharacteristics && loopCharacteristics.$type === 'bpmn:MultiInstanceLoopCharacteristics') {
        isMultiInstance.value = true;
        multiInstanceType.value = loopCharacteristics.isSequential ? 'sequential' : 'parallel';
        // 获取完成条件
        if (loopCharacteristics.completionCondition) {
          completionCondition.value = loopCharacteristics.completionCondition.body || '';
        }
      } else {
        // 重置会签设置
        isMultiInstance.value = false;
        multiInstanceType.value = 'parallel';
        completionCondition.value = '';
      }
    }

    // 服务任务属性
    if (isServiceTask.value) {
      const classValue = getFlowableProperty(businessObject, 'class');
      const expressionValue = getFlowableProperty(businessObject, 'expression');
      const delegateExpressionValue = getFlowableProperty(businessObject, 'delegateExpression');

      if (classValue) {
        serviceType.value = 'class';
        serviceValue.value = String(classValue);
      } else if (expressionValue) {
        serviceType.value = 'expression';
        serviceValue.value = String(expressionValue);
      } else if (delegateExpressionValue) {
        serviceType.value = 'delegateExpression';
        serviceValue.value = String(delegateExpressionValue);
      } else {
        serviceType.value = 'class';
        serviceValue.value = '';
      }
    }

    // 连接线属性
    if (isSequenceFlow.value) {
      const conditionExpr = businessObject.conditionExpression;
      conditionExpression.value = conditionExpr ? (conditionExpr.body || '') : '';

      // 获取条件类型 - 优先检查标准BPMN默认流属性
      const isDefaultFlow = businessObject.default || businessObject['default'] === true;
      const savedConditionType = getFlowableProperty(businessObject, 'conditionType');

      if (isDefaultFlow) {
        conditionType.value = 'default';
      } else if (savedConditionType) {
        conditionType.value = savedConditionType;
      } else if (conditionExpression.value) {
        conditionType.value = 'conditional';
      } else {
        conditionType.value = 'normal';
      }
    }

    // 加载表单字段权限控制
    if (isUserTask.value) {
      const formFieldPermissionsStr = getFlowableProperty(businessObject, 'formFieldPermissions');
      if (formFieldPermissionsStr) {
        try {
          const permissionsData = JSON.parse(String(formFieldPermissionsStr));
          if (permissionsData.fields && Array.isArray(permissionsData.fields)) {
            formFieldPermissions.value = permissionsData.fields;
          }
        } catch {
          formFieldPermissions.value = [];
        }
      } else {
        formFieldPermissions.value = [];
      }
    }

    // 加载操作权限控制
    const operationPermissionsStr = getFlowableProperty(businessObject, 'operationPermissions');
    if (operationPermissionsStr) {
      try {
        const permissionsData = JSON.parse(String(operationPermissionsStr));
        if (permissionsData.operations && Array.isArray(permissionsData.operations)) {
          operationPermissions.value = permissionsData.operations;
        }
      } catch {
        // 如果解析失败，使用默认配置
        operationPermissions.value = [
          { name: '同意', alias: '同意', enabled: true, status: '审批通过' },
          { name: '拒绝', alias: '拒绝', enabled: true, status: '审批拒绝' },
          { name: '转交', alias: '转交', enabled: true, status: '审批中' },
          { name: '回退', alias: '回退', enabled: true, status: '已回退' },
          { name: '前加签', alias: '前加签', enabled: true, status: '审批中' },
          { name: '后加签', alias: '后加签', enabled: true, status: '审批中' }
        ];
      }
    }
  };

  // 安全获取Flowable属性的辅助函数
  const getFlowableProperty = (businessObject: any, propertyName: string) => {
    try {
      // 尝试使用get方法
      if (businessObject && typeof businessObject.get === 'function') {
        const value = businessObject.get(`flowable:${propertyName}`);
        if (value !== undefined && value !== null) {
          return value;
        }
      }

      // 如果get方法失败或不存在，尝试直接访问属性
      if (businessObject) {
        return businessObject[`flowable:${propertyName}`] ||
               businessObject.$attrs?.[`flowable:${propertyName}`] ||
               businessObject[propertyName]; // 对于某些特殊情况，直接访问属性名
      }

      return undefined;
    } catch (error) {
      console.warn(`Failed to get flowable property: ${propertyName}`, error);
      return undefined;
    }
  };

  // 清除属性
  const clearProperties = () => {
    elementId.value = '';
    elementName.value = '';
    processId.value = '';
    processName.value = '';

    // 清空用户任务属性
    candidateUsers.value = [];
    candidateGroups.value = [];
    dueDate.value = '';
    formKey.value = '';

    // 清空审批模式
    approvalMode.value = 'assignee';

    // 清空审批人为空时处理策略
    emptyAssigneeStrategy.value = '';

    // 清空自动同意设置
    autoApproveSettings.value = [];

    conditionExpression.value = '';
    conditionType.value = 'normal';
    serviceType.value = 'class';
    serviceValue.value = '';

    // 清空会签设置
    isMultiInstance.value = false;
    multiInstanceType.value = 'parallel';
    completionCondition.value = '';

    // 清空权限控制
    formFieldPermissions.value = [];
    operationPermissions.value = [
      { name: '同意', alias: '同意', enabled: true, status: '审批通过' },
      { name: '拒绝', alias: '拒绝', enabled: true, status: '审批拒绝' },
      { name: '转交', alias: '转交', enabled: true, status: '审批中' },
      { name: '回退', alias: '回退', enabled: true, status: '已回退' },
      { name: '前加签', alias: '前加签', enabled: true, status: '审批中' },
      { name: '后加签', alias: '后加签', enabled: true, status: '审批中' }
    ];
  };

  // 监听选择元素变化
  onMounted(() => {
    if (!props.modeler) return;

    const eventBus = props.modeler.get<EventBus>('eventBus');
    if (!eventBus) return;

    // 选择元素时
    eventBus.on('selection.changed', (e: { newSelection: any[] }) => {
      const { newSelection } = e;
      let element = newSelection[0] || null;
      if (!element) {
        element = props.modeler.get<ElementRegistry>('elementRegistry').find((el: any) => el.type === 'bpmn:Process')
        if (!element) {
          console.log('No Element found!')
          return
        }
      }
      selectedElement.value = markRaw(element);

      if (element) {
        loadElementProperties(element);
      } else {
        clearProperties();
      }
    });

    // 元素属性变化时
    eventBus.on('element.changed', (e: { element: any }) => {
      const { element } = e;
      if (selectedElement.value && selectedElement.value.id === element.id) {
        loadElementProperties(element);
      }
    });
  });

  return {
    // 状态
    selectedElement,
    elementId,
    elementName,
    activeTab,
    assignee,
    // 流程基本属性
    processId,
    processName,
    processDescription,

    // 用户任务属性
    candidateUsers,
    candidateGroups,
    dueDate,
    formKey,

    // 审批模式
    approvalMode,

    // 审批人为空时处理策略
    emptyAssigneeStrategy,

    // 自动同意设置
    autoApproveSettings,

    // 会签设置
    isMultiInstance,
    multiInstanceType,
    completionCondition,

    conditionExpression,
    conditionType,
    serviceType,
    serviceValue,

    // 表单字段权限控制
    formFieldPermissions,

    // 操作权限控制
    operationPermissions,

    // 计算属性
    isProcess,
    isTask,
    isUserTask,
    isServiceTask,
    isSequenceFlow,
    serviceTypeLabel,
    builtinButtonOptions,

    // 方法
    updateProperty,
    updateFlowableProperty,
    handleAssigneeChange,
    handleCandidateUsersChange,
    handleCandidateGroupsChange,

    // 审批模式处理方法
    updateApprovalMode,

    // 审批人为空时处理策略方法
    updateEmptyAssigneeStrategy,

    // 自动同意设置方法
    updateAutoApproveSettings,

    handleServiceTypeChange,
    updateServiceImplementation,
    updateConditionExpression,
    updateConditionType,

    // 会签相关方法
    toggleMultiInstance,
    updateMultiInstanceType,
    updateCompletionCondition,

    updateFormFieldPermissions,
    addFormField,
    removeFormField,
    updateFieldPermission,
    importFormFields,
    updateOperationPermissions,
    updateOperationPermission
  };
}
